<?php
/**
 * 好友分组管理
 * 
 * @author 	jiaowei<fanzhanao@178.com>
 * @version $Id: group.php 10130 2010-08-20 06:59:02Z fanzhanao $
 */
class friends_controller_group extends SnsController
{	
	/**
	 * friends_model_group
	 *
	 * @var obj
	 */
	private $_group = null;
	
	/**
	 * 模块缓存前缀
	 *
	 * @var str
	 */
	private $_module = null;
	
	public function __construct($app, $controller)
	{
		parent::__construct($app, $controller);
		$this->headerView = $this->viewDir . '/sns/_header.phtml';
		$this->frameView = VIEW_PATH.'/sns/index.phtml';
		$this->_group = new friends_model_group();
		$this->_module = $app . '_' . $controller;
		$this->requireLogin();
	}
	
	/**
	 * 添加好友分组
	 *
	 * @display false
	 */
	public function add_group_action()
	{
		$this->_renderJson();
		$uid = self::$login['uid'];
		
		$group_name = _('group_name', '');
		if (empty($group_name)) {
			$this->ret = self::failure(Error::ERROR_WRONG_PARAMS, '分组名称不能为空');
			return;
		}
		
		$group_info = $this->_group->getGroupByName($uid, $group_name);
		if ($group_info['group_name']) {
			$this->ret = self::failure(Error::ERROR_WRONG_PARAMS, '该分组已存在');
			return ;
		}
		
		$data = array(
			'uid' 		 => $uid,
			'group_name' => $group_name,
			'group_nums' => 0
		);
		
		if (!($groupId = $this->_group->addGroup($data))) {
			$this->ret = self::failure(Error::ERROR_UNKNOWN, '添加分组失败,请重试');
			return;
		}
		$this->ret = self::success(array('group_name' => htmlspecialchars($group_name)));
		
		//增加用户的分组id list cache
		MemRow::incrList($groupId, array($this->_group, 'getGroupListId', array($uid)));

		//缓存$groupId详细信息
		$cacheRowKey = MemRow::genRowKey($this->_module, $groupId);
		MemRow::mset($cacheRowKey, array('group_id' => $groupId) + $data);
	}
	
	/**
	 * 编辑好友分组
	 *
	 * @display false
	 */
	public function edit_group_action()
	{
		$this->_renderJson();
		$uid = self::$login['uid'];
		
		$group_id	= _('group_id', '');
		if (empty($group_id)) {
			$this->ret = self::failure(Error::ERROR_WRONG_PARAMS, '分组ID不能为空');
			return ;
		}
		
		$group_name = _('group_name', '');
		if (empty($group_name)) {
			$this->ret = self::failure(Error::ERROR_WRONG_PARAMS, '分组名称不能为空');
			return ;
		}
		
		$group_info = $this->_group->getGroup($group_id);
		if ($uid != $group_info['uid']) {
			$this->ret = self::failure(Error::ERROR_WRONG_PARAMS, '您不能修改此分组');
			return ;
		}
		
		$group_info = $this->_group->getGroupByName($uid, $group_name, $group_id);
		if ($group_info['group_name']) {
			$this->ret = self::failure(Error::ERROR_WRONG_PARAMS, '该分组已存在');
			return ;
		}
		
		$data = array('group_name' => $group_name);
		
		if (!$this->_group->editGroup($data, $group_id)) {
			$this->ret = self::failure(Error::ERROR_UNKNOWN, '修改分组失败,请重试');
			return ;
		}
		$this->ret = self::success(array('group_name' => htmlspecialchars($group_name)));
		
		//cache update
		if ($groupInfo = MemRow::mget($this->_module, $group_id, array($this->_group, 'getGroupRow'))) {
			$groupInfo['group_name'] = $group_name;
			$cacheRowKey = MemRow::genRowKey($this->_module, $group_id);
			MemRow::mset($cacheRowKey, $groupInfo);
		}
	}
	
	/**
	 * 删除好友分组
	 *
	 * @display false
	 */
	public function del_group_action()
	{
		$this->_renderJson();
		$uid = self::$login['uid'];
		
		$group_id = _('group_id', '');
		if (empty($group_id)) {
			$this->ret = self::failure(Error::ERROR_WRONG_PARAMS, '分组ID不能为空');
			return ;
		}
		
		$group_info = $this->_group->getGroup($group_id);
		if ($uid != $group_info['uid']) {
			$this->ret = self::failure(Error::ERROR_WRONG_PARAMS, '您不能删除此分组');
			return ;
		}
	
		if (!$this->_group->delGroup($uid, $group_id)) {
			$this->ret = self::failure(Error::ERROR_UNKNOWN, '删除分组失败,请重试');
			return ;
		}

		//删除从属于该分组的好友列表
		$this->_group->delFriendFromGroup($uid, 0, $group_id);
		
		$this->ret = self::success();
		
		//减少用户的分组id list cache
		MemRow::decrList($group_id, array($this->_group, 'getGroupListId', array($uid)));
	}
	
	/**
	 * 获取好友分组信息
	 *
	 * @display false
	 */
	public function get_friend_group_action()
	{
		$this->_renderJson();
		$uid = self::$login['uid'];
		$friend_id = _('friend_id', '');
		
		//好友所属的分组列表
		$groups = $this->_group->getFriendGroup($uid, $friend_id);
		
		$groupIds = array();
		foreach ($groups AS $v) {
			$groupIds[] = $v['group_id'];
		}
			
		//获取所有分组id
		$allGroupIds = MemRow::getListId(array($this->_group, 'getGroupListId', array($uid)));
		
		//好友分组
		$allGroups   = MemRow::mget($this->_module, $allGroupIds, array($this->_group, 'getGroupRow'));

		foreach ($allGroups as $k => $v) {
			if (in_array($v['group_id'], $groupIds)) {
				$allGroups[$k]['checked'] = 1;
			}
		}
		//exit;
		$this->ret = array('result' => true, 'data' => $allGroups);
	}
	
	
	/**
	 * 添加好友到某个分组
	 *
	 * @display false
	 */
	public function add_friend_group_action()
	{
		$this->_renderJson();
		$uid = self::$login['uid'];
		
		$group_id  = _('group_id', '');
		$friend_id = _('friend_id', '');
		
		if (!$friend_id) {
			$this->ret = self::failure(Error::ERROR_WRONG_PARAMS, '好友ID不能为空');
			return ;
		}
		
		//好友所属的所有分组
		$groups = $this->_group->getFriendGroup($uid, $friend_id);
		if ($groups) {
			//删除所有分组下该好友的从属关系
			$this->_group->delFriendFromGroup($uid, $friend_id);
			
			$groupIds = array();
			foreach ($groups AS $v) {
				$groupIds[] = $v['group_id'];
				MemRow::decrList($friend_id, array($this->_group, 'getListId', array($uid, $v['group_id'])));
				if ($groupInfo = MemRow::mget($this->_module, $v['group_id'], array($this->_group, 'getGroupRow'))) {
					if ($groupInfo['group_nums'] > 0) {
						$groupInfo['group_nums'] -= 1;
					}
					MemRow::mset(MemRow::genRowKey($this->_module, $v['group_id']), $groupInfo);
				}
			}
			
			//修改分组好友人数 -1
			$this->_group->editGroupFriendsNums($groupIds);
		}
		
		if ($group_id) {
			//分组不为空
			$group_id = explode(',', $group_id);
			
			if (!$this->_group->addFriendToGroup($uid, $friend_id, $group_id)) {
				$this->ret = self::failure(Error::ERROR_UNKNOWN, '添加失败,请重试');
				return;
			}

			//修改分组好友人数 +1
			$this->_group->editGroupFriendsNums($group_id, true);
			foreach ($group_id as $id) {
				MemRow::incrList($friend_id, array($this->_group, 'getListId', array($uid, $id)));
				if ($groupInfo = MemRow::mget($this->_module, $id, array($this->_group, 'getGroupRow'))) {
					$groupInfo['group_nums'] += 1;
					MemRow::mset(MemRow::genRowKey($this->_module, $id), $groupInfo);
				}
			}
		}
		
		$this->ret = self::success();
	}
	
	/**
	 * 删除分组里的好友
	 *
	 * @display false
	 */
	public function del_friend_group_action()
	{
		$this->_renderJson();
		$uid = self::$login['uid'];
		
		$group_id  = _('group_id', '');
		$friend_id = _('friend_id', '');
		if (!$group_id) {
			$this->ret = self::failure(Error::ERROR_WRONG_PARAMS, '分组ID不能为空');
			return ;
		}
		
		if (!$friend_id) {
			$this->ret = self::failure(Error::ERROR_WRONG_PARAMS, '好友ID不能为空');
			return ;
		}
		
		if (!$this->_group->checkFriendGroup($uid, $group_id, $friend_id)) {
			$this->ret = self::failure(Error::ERROR_WRONG_PARAMS, '您不能移除此分组用户');
			return ;
		}
		
		
		if (!$this->_group->delFriendFromGroup($uid, $friend_id, $group_id)) {
			$this->ret = self::failure(Error::ERROR_UNKNOWN, '删除失败,请重试');
			return ;
		} 
				
		//修改分组好友人数 -1
		$this->_group->editGroupFriendsNums($group_id);
		MemRow::decrList($friend_id, array($this->_group, 'getListId', array($uid, $group_id)));
		if ($groupInfo = MemRow::mget($this->_module, $group_id, array($this->_group, 'getGroupRow'))) {
			if ($groupInfo['group_nums'] > 0) {
				$groupInfo['group_nums'] -= 1;
			}
			MemRow::mset(MemRow::genRowKey($this->_module, $group_id), $groupInfo);
		}
		$this->ret = self::success();
	}
	
	/**
	 * 获取好友列表 (例如发送礼物好友列表)
	 *
	 * @display false
	 */
	public function get_group_user_action()
	{
		$this->_renderJson();
		$group_id = _('group_id', 0);
		$uid 	  = self::$login['uid'];
		
		if ($group_id) {
			if ('!guild' == $group_id) {
				$allFriendIds = MemRow::getListId(array(Model::factory('friends_model_guild'), 'getListId', array($uid)));
			} else {
				$allFriendIds = MemRow::getListId(array($this->_group, 'getListId', array($uid, $group_id)));
			}
		} else {//全部好友
			$allFriendIds = friends_util_friendutil::getFriendIds($uid);
		}
		$friends = friends_util_friendutil::getUserInfo($allFriendIds);
		$result = array();
		foreach ($friends as $key => $val) {
			$result[] = array('uid' => $val['id'], 'username' => $val['username']);
		}
		$this->ret = self::success($result);
	}
	
	/**
	 * 获取所有好友分组
	 *
	 * @display false
	 */
	public function get_all_group_action()
	{
		$this->_renderJson();
		$uid = self::$login['uid'];
		
		//获取所有分组id
		$allGroupIds = MemRow::getListId(array($this->_group, 'getGroupListId', array($uid)));
		
		//好友分组
		$allGroups   = MemRow::mget($this->_module, $allGroupIds, array($this->_group, 'getGroupRow'));

		$result = array();
		foreach ($allGroups as $key => $val) {
			$result[$val['group_id']] = array('group_name' => $val['group_name'], 'group_nums' => $val['group_nums']);
		}
		
		$this->ret = self::success($result);
	}
	
	/**
	 * 好友分页列表
	 *
	 * @display true
	 */
	public function get_list_action()
	{
		$uid   		 = self::$login['uid'];
		$currPage 	 = _('page', 1);
		$this->group = isset($_GET['group']) ? (int) $_GET['group'] : '';
		
		//全部好友数
		$allFriendIds = friends_util_friendutil::getFriendIds($uid);

		//已分组好友
		$groupFriends = $this->_group->getGroupedFriends($uid);
				
		switch ($this->group) {
			//所有好友列表
			case '':
				$friendsIds = $allFriendIds;
				break;
				
			//未分组好友列表
			case '0':
				$friendsIds = array_diff($allFriendIds, $groupFriends);
				break;
				
			//分组好友列表
			default:
				//分组好友
				$friendsIds = MemRow::getListId(array($this->_group, 'getListId', array($uid, $this->group)));
		} //end switch

		list($pageListId, $pageInfo) = MemRow::getPageListId($friendsIds, $currPage, friends_model_group::PAGE_SIZE);	
		
		$pageData = friends_util_friendutil::getUserInfo($pageListId);
		
//		print_r($pageData);
		
		
		if ($remarks = Model::factory('friends_model_data')->getRemark($uid))
			foreach ($pageData as $k => $v) 
				$pageData[$k]['remark'] = isset($remarks[$v['uid']]) ? $remarks[$v['uid']] : '';
		
	
		
		
	
		//获取所有分组id
		//$allGroupIds = MemRow::getListId(array($this->_group, 'getGroupListId', array($uid)));
		$allGroupIds = $this->_group->getGroupListId($uid);
		if (!$allGroupIds) {
			$defaultGroups = array('现在同事', '以前同事', '同学', '漫画好友');
			foreach ($defaultGroups as $group_name) {
				$data = array('uid' => $uid, 'group_name' => $group_name, 'group_nums' => 0);
				
				$groupId = $this->_group->addGroup($data);
				
				if ($groupId) {
					//增加用户的分组id list cache
					$allGroupIds = MemRow::incrList($groupId, array($this->_group, 'getGroupListId', array($uid)));
			
					//缓存$groupId详细信息
					MemRow::mset(MemRow::genRowKey($this->_module, $groupId), array('group_id' => $groupId) + $data);
				}
			}
		}

		//好友分组
		$this->allUserGroups = MemRow::mget($this->_module, $allGroupIds, array($this->_group, 'getGroupRow'));
	
//		var_dump($this->allUserGroups);
		//所有好友数
		$this->allUserNums = count($allFriendIds);
		
		//未分组好友数
		$this->noGroupUserNums = $this->allUserNums - count($groupFriends);
		
		$this->pageInfo = $pageInfo;
		
		$this->ret 		= $pageData;
		
        $this->view = 'get_list';

//        $this->right_view = 'group/part_list_right.phtml';
	}
	
	/**
	 * 搜索会员
	 */
	
	public function search_action(){
		$page	=	_('page',1);
		$k		=	_('k');
		
		$exclude = false;
		
		if(self::$login['uid']){
			$exclude	=	self::$login['uid'];
			if(is_numeric($k) && (int)$k = self::$login['uid'])	{
				$k = '';			
			}
		}
		
		$list	=	member_util_interface::search($k,$page,20,$exclude);
		
		$page	=	$this->genPages($list['INFO'],array('k'=>$v));
		
		$this->ret	=	array('data'=>$list,'pages' => $page);
		$this->view	=	'part_search';
	}
	
	
	
	
	/**
	 * 我的好友的好友的共同好友
	 *
	 * @display true
	 */
	public function mutu_friends_action()
	{
		$uid 	  = (int) self::$login['uid'];
		$currPage = isset($_GET['page']) ? (int) $_GET['page'] : 1;
		$pageSize = 20;
	
		$cacheKey = $this->app . '_' . $this->controller . '_' . $this->action . '_' . $uid;//cache key	
		$leftTime = 3600;//cache lefttime

		if (false === ($commFriend = MemRow::getCache($cacheKey))) {//false 会返回空字符串 null会返回null
			$commFriend = $this->_group->commfriendsOfMyFriends($uid);
			MemRow::mset($cacheKey, $commFriend, $leftTime);
		}
		
		$this->ret 		= array();
		$this->pageInfo = array();
		
		if ($commFriend) {
			$offset 	= ($currPage - 1) * $pageSize;
			$count 		= count($commFriend);
			$totalPage  = ceil($count / $pageSize);
			$commFriend = array_slice($commFriend, $offset, $pageSize, true);
			
			$userId 	= array_keys($commFriend);
			$userInfo 	= friends_util_cache::getUserInfo($userId);
			foreach ($userInfo as $k => $v)
				$userInfo[$k]['comm_nums'] = $commFriend[$v['id']];

			$this->ret 		= $userInfo;		
			$this->pageInfo = array('COUNT' => $count, 'PAGE' => $currPage, 'PAGESIZE' => $pageSize, 'PAGECOUNT' => $totalPage);
		}
	}
	
	/**
	 * 两个用户共同好友
	 *
	 * @return unknown
	 * 
	 * @display false
	 */
	public function get_common_friend_action()
	{
		$this->_renderJson();
		
		$uid1   = (int) self::$login['uid'];
		$uid2   = isset($_POST['uid']) ? (int) $_POST['uid'] : 0;
		$result = Model::factory('friends_model_data')->commFriends($uid1, $uid2);
		
		$this->ret = self::success($result);
	}
}
